#include "attendancerulesservice.h"
#include <QTime>


bool AttendanceRulesService::insertDefaultRule()
{
    // 插入默认规则SQL（标准工时制：早9点上班，晚6点下班，签到8:30开始，签退18:30结束）
    QString sql = R"(
                  INSERT INTO attendance_rules (
                  rule_name, work_start, work_end,
                  checkin_start, checkout_end, is_default
                  ) VALUES (
                  '标准工时制', '09:00:00', '18:00:00',
                  '08:30:00', '18:30:00', 1
                  )
                  )";

    // 通过 SqliteManager 执行插入（利用其线程安全和错误处理）
    bool success = dbManager->execNonQuery(sql);
    if (!success) {
        // 捕获唯一约束冲突（已存在默认规则）
        QSqlQuery query = SqliteManager::getInstance()->execQuery("SELECT last_insert_rowid()");
        qWarning() << "Insert default rule failed: " << dbManager->getSqlDatabase().lastError().text();
        return false;
    }

    qDebug() << "Default attendance rule inserted successfully";
    return true;
}

QJsonArray AttendanceRulesService::getRulesByName(const QString& ruleName)
{
    QJsonArray array;
    if (ruleName.isEmpty()) {
        qWarning() << "Rule name cannot be empty";
        return array;
    }

    // 构造查询SQL，使用参数化查询
    QString sql = "SELECT * FROM attendance_rules WHERE rule_name = :rule_name";

    // 通过 SqliteManager 执行带参数的查询
    QSqlQuery query = dbManager->execQueryWithParams(
                sql,
                [&](QSqlQuery& q) {
            q.bindValue(":rule_name", ruleName);  // 绑定参数
            return true;
}
            );

    // 遍历查询结果，转换为JSON数组
    while (query.next()) {
        QJsonObject obj;
        obj["rule_id"] = query.value("rule_id").toInt();
        obj["rule_name"] = query.value("rule_name").toString();
        obj["work_start"] = query.value("work_start").toString();  // TIME类型转字符串
        obj["split_time"] = query.value("split_time").toString();
        obj["work_end"] = query.value("work_end").toString();
        obj["checkin_start"] = query.value("checkin_start").toString();
        obj["checkout_end"] = query.value("checkout_end").toString();
        obj["is_default"] = query.value("is_default").toInt();  // 新增默认规则字段
        array.append(obj);
    }

    return array;
}

// 修改规则
bool AttendanceRulesService::updateRulesByRuleName(
        const QString& rule_name,
        const QTime& work_start,
        const QTime& work_end,
        const QTime& split_time,
        const QTime& checkin_start,
        const QTime& checkout_end)
{
    if (rule_name.isEmpty()) {
        qWarning() << "Rule name cannot be empty";
        return false;
    }
    if (!work_start.isValid() || !work_end.isValid()
            || !checkin_start.isValid() || !checkout_end.isValid()) {
        qWarning() << "Invalid time parameters";
        return false;
    }

    // 构造更新SQL
    QString sql = R"(
                  UPDATE attendance_rules
                  SET work_start = :work_start,
                  work_end = :work_end,
                  split_time = :split_time,
                  checkin_start = :checkin_start,
                  checkout_end = :checkout_end
                  WHERE rule_name = :rule_name
                  )";

    // 通过 SqliteManager 执行带参数的更新
    bool success = dbManager->execNonQueryWithParams(
                sql,
                [&](QSqlQuery& q) {
            // 绑定参数（QTime转TIME字符串格式）
            q.bindValue(":work_start", work_start.toString("HH:mm:ss"));
            q.bindValue(":work_end", work_end.toString("HH:mm:ss"));
            q.bindValue(":split_time", split_time.toString("HH:mm:ss"));
            q.bindValue(":checkin_start", checkin_start.toString("HH:mm:ss"));
            q.bindValue(":checkout_end", checkout_end.toString("HH:mm:ss"));
            q.bindValue(":rule_name", rule_name);
            return true;
}
            );

    // 检查更新结果（是否有记录被影响）
    if (success) {
        // 再次查询受影响行数（因 execNonQueryWithParams 不直接返回行数）
        QSqlQuery query = dbManager->execQuery(
                    QString("SELECT changes() AS affected_rows")
                    );
        if (query.next() && query.value("affected_rows").toInt() <= 0) {
            qWarning() << "No rule found with name:" << rule_name;
            return false;
        }
        return true;
    } else {
        qWarning() << "Update failed (SQL error)";
        return false;
    }
}
